﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Reflection;
using EstoqueUnifeiADO.Lib.Class;

namespace EstoqueUnifeiADO.Controles
{
    public partial class ctrlItemMarca : System.Web.UI.UserControl
    {
        #region Propriedades e atributos

        public string Key
        {
            set
            {
                hfKey.Value = value;
                fvItem.DataBind();
            }
        }
        protected string GrupoDeValidadacao
        {
            get { return "Group" + this.ClientID; }

        }
        public event DetailUpdatedHandler DetailUpdated;
        #endregion

        #region Eventos
        protected void odsItem_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {

        }
        protected void FormView1_DataBound(object sender, EventArgs e)
        {

            if ((fvItem.CurrentMode == FormViewMode.Insert) || (fvItem.CurrentMode == FormViewMode.Edit))
            {
                SetFormValidationSummary(fvItem.Row.Controls);

            }



        }

        protected void fvItem_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
        {
            if (e.Exception != null)
            {
                e.ExceptionHandled = true;
                AddError("Erro ao atualizar o registro:" + e.Exception.InnerException.Message);

            }
            else
            {
                ShowMessage("Item atualizado com sucesso");
            }



        }

        protected void fvItem_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            fvItem.DataBind();


        }

        protected void odsItem_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
        {
            if (e.Exception != null)
            {
                e.ExceptionHandled = true;
                AddError("Erro ao inserir o registro:" + e.Exception.InnerException.Message);

            }
            else
            {


                if (DetailUpdated != null)
                {
                    DetailUpdated(sender, new DetailUpdatedArgs()
                    {
                        ReturnValue = hfKey.Value,
                        SystemMessage = "Item inserido com sucesso"
                    });

                    hfKey.Value = e.ReturnValue.ToString();
                }
                else
                {
                    hfKey.Value = e.ReturnValue.ToString();
                    ShowMessage("Item inserido com sucesso");
                }

            }
        }
        #endregion

        #region Métodos da página
        protected void Page_Load(object sender, EventArgs e)
        {
            vsPage.ValidationGroup = this.GrupoDeValidadacao;

            HideMessage();

        }
        #endregion

        #region Métodos
        public void SetReadOnly()
        {
            if (fvItem.CurrentMode == FormViewMode.Insert || fvItem.CurrentMode == FormViewMode.Edit)
                fvItem.ChangeMode(FormViewMode.ReadOnly);
        }
        public void SetEditMode()
        {
            fvItem.ChangeMode(FormViewMode.Edit);

        }
        public void SetInsertMode()
        {
            fvItem.ChangeMode(FormViewMode.Insert);

        }
        protected void AddError(String Erro)
        {
            this.Page.Validators.Add(new CustomValidator()
            {
                IsValid = false,
                ErrorMessage = Erro,
                Display = ValidatorDisplay.Dynamic,
                ValidationGroup = this.GrupoDeValidadacao

            });
        }
        protected void ShowMessage(string mensagem)
        {
            lbMensagem.Text = mensagem;
            pnlMensagem.Visible = true;

        }
        protected void HideMessage()
        {
            pnlMensagem.Visible = false;
            lbMensagem.Text = string.Empty;
        }


        private void SetFormValidationSummary(ControlCollection controles)
        {


            foreach (Control item in controles)
            {
                if (item is BaseValidator)
                {
                    ((BaseValidator)item).Text = "*";
                    ((BaseValidator)item).ForeColor = Color.Red;
                    ((BaseValidator)item).Display = ValidatorDisplay.Dynamic;
                    ((BaseValidator)item).ToolTip = ((BaseValidator)item).ErrorMessage;
                }
                PropertyInfo campo = item.GetType().GetProperty("ValidationGroup");
                if (campo != null)
                    if (campo.CanWrite)
                        campo.SetValue(item, this.GrupoDeValidadacao, null);
                if (item.Controls.Count > 0)
                    SetFormValidationSummary(item.Controls);

            }

        }
        #endregion
    }
}